/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.core.ehcache.hibernate;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.TerracottaConfiguration.ValueMode;
import net.sf.ehcache.hibernate.EhCacheRegionFactory;

import org.hibernate.cache.CacheException;
import org.hibernate.cfg.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <pre>
 * 
 * 将Ehcache的初始化部分抽离出来
 * 
 * 注意：如果更换Ehcache版本需要根据情况修改该类
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public abstract class AbstractMultiConfigAwareEhCacheRegionFactory extends EhCacheRegionFactory {
	private static final Logger logger = LoggerFactory.getLogger(MultiConfigAwareEhCacheRegionFactory.class);

	public AbstractMultiConfigAwareEhCacheRegionFactory(Properties prop) {
		super(prop);
	}

	@Override
	public void start(Settings settings, Properties properties) throws CacheException {
		this.settings = settings;
		if (manager != null) {
			logger.warn("Attempt to restart an already started EhCacheRegionFactory. Use sessionFactory.close() "
					+ " between repeated calls to buildSessionFactory. Using previously created EhCacheRegionFactory."
					+ " If this behaviour is required, consider using SingletonEhCacheRegionFactory.");
			return;
		}

		try {
			String configurationResourceName = null;
			if (properties != null) {
				configurationResourceName = (String) properties.get(NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME);
			}
			if (configurationResourceName == null || configurationResourceName.length() == 0) {
				Configuration configuration = parseConfiguration();
				manager = new CacheManager(configuration);
			} else {
				URL url;
				try {
					url = new URL(configurationResourceName);
				} catch (MalformedURLException e) {
					url = loadResource(configurationResourceName);
				}
				Configuration configuration = loadAndCorrectConfiguration(url);
				manager = new CacheManager(configuration);
			}
			mbeanRegistrationHelper.registerMBean(manager, properties);
		} catch (net.sf.ehcache.CacheException e) {
			if (e.getMessage().startsWith("Cannot parseConfiguration CacheManager. Attempt to create a new instance of " + "CacheManager using the diskStorePath")) {
				throw new CacheException("Attempt to restart an already started EhCacheRegionFactory. "
						+ "Use sessionFactory.close() between repeated calls to buildSessionFactory. " + "Consider using SingletonEhCacheRegionFactory. Error from ehcache was: "
						+ e.getMessage());
			} else {
				throw new CacheException(e);
			}
		}
	}

	private Configuration loadAndCorrectConfiguration(URL url) {
		Configuration config = parseConfiguration(url);
		if (config.getDefaultCacheConfiguration().isTerracottaClustered()) {
			if (ValueMode.IDENTITY.equals(config.getDefaultCacheConfiguration().getTerracottaConfiguration().getValueMode())) {
				logger.warn("The default cache value mode for this Ehcache configuration is \"identity\". This is incompatible with clustered "
						+ "Hibernate caching - the value mode has therefore been switched to \"serialization\"");
				config.getDefaultCacheConfiguration().getTerracottaConfiguration().setValueMode(ValueMode.SERIALIZATION.name());
			}
		}

		for (CacheConfiguration cacheConfig : config.getCacheConfigurations().values()) {
			if (cacheConfig.isTerracottaClustered()) {
				if (ValueMode.IDENTITY.equals(cacheConfig.getTerracottaConfiguration().getValueMode())) {
					logger.warn("The value mode for the {0} cache is \"identity\". This is incompatible with clustered Hibernate caching - "
							+ "the value mode has therefore been switched to \"serialization\"", cacheConfig.getName());
					cacheConfig.getTerracottaConfiguration().setValueMode(ValueMode.SERIALIZATION.name());
				}
			}
		}
		return config;
	}

	protected abstract Configuration parseConfiguration();

	protected abstract Configuration parseConfiguration(URL url);
}
